package com.cnfangmao.masterdata.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.cnfangmao.masterdata.common.response.ResCodeEnum;
import com.cnfangmao.masterdata.common.util.MD5Utils;
import com.cnfangmao.masterdata.common.response.ResBody;
import com.cnfangmao.masterdata.dto.LoginDto;

@Api(tags = "0-0、登录-用户登录管理")
@RestController
@RequestMapping(path = "/auth")
public class AuthController {

	private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

	/**
	 * 登录
	 */
	@ApiOperation(value = "登录", notes = "登录")
	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	@ApiImplicitParam(name = "dto", value = "登录信息", required = true, paramType = "body", dataType = "LoginDto")
	public ResBody<?> login(@RequestBody LoginDto dto) {
		Integer code = 0;
		String msg = "";

		if (dto.getUserCode() == null || dto.getUserCode().isEmpty()) {
			return ResBody.custom(ResCodeEnum.PARAM_NULL.getCode(), "用户名为空");
		}

		String md5Password = MD5Utils.getMD516(dto.getPassword());

		// 1、获取Subject实例对象
		Subject currentUser = SecurityUtils.getSubject();
		// 2、将用户名和密码封装到UsernamePasswordToken
		UsernamePasswordToken token = new UsernamePasswordToken(dto.getUserCode(), md5Password);

		// 3、认证
		try {
			currentUser.login(token);// 传到MyAuthorizingRealm类中的方法进行认证

			return ResBody.custom(ResCodeEnum.SUCCESS.getCode(), "", true);
		} catch (UnknownAccountException e) {
			code = ResCodeEnum.ACCOUNT_NO_EXISTIS.getCode();
			msg = "账号不存在：";
		} catch (IncorrectCredentialsException e) {
			code = ResCodeEnum.ACCOUNT_NO_EXISTIS.getCode();
			msg = "密码不正确：";
		} catch (AuthenticationException e) {
			code = ResCodeEnum.FAIL.getCode();
			msg = "用户验证失败";
		}

		return ResBody.custom(code, msg);
	}

	/**
	 * 退出登录
	 */
	@ApiOperation(value = "退出登录", notes = "退出登录")
	@RequestMapping(value = "/logout.do", method = RequestMethod.POST)
	public ResBody<?> logout(HttpSession session) {
		try {
			Subject subject = SecurityUtils.getSubject();
			subject.logout();

			return ResBody.custom(ResCodeEnum.SUCCESS.getCode(), "退出成功", true);
		} catch (Exception ex) {
			logger.error("LoginController logout err, ", ex);
			return ResBody.custom(ResCodeEnum.FAIL.getCode(), "退出失败", true);
		}
	}
}
